<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { empIndex, empDEL, empEdit, departmentSelect } from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
// import { TableColumn } from '@/types/table'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id
const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}
const { push } = useRouter()
const { register, tableObject, methods } = useTable<TableData>({
  getListApi: empIndex,
  delListApi: empDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: ''
})

const { getList, setSearchParams } = methods

getList()

// const { emitter } = useEmitt()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const { t } = useI18n()

const AddressList = ref([])
const sex = reactive([
  { label: '男', value: '0' },
  { label: '女', value: '1' }
])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'id',
    label: 'ID',
    search: {
      show: false
    },
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'name',
    label: t('traveling.fullName'),
    search: {
      show: true
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'username',
    width: '260px',
    label: t('login.username'),
    form: {
      show: true
    },
    detail: {
      show: false
    },
    table: {
      show: true
    }
  },
  {
    field: 'password',
    width: '260px',
    label: t('login.password'),
    search: {
      show: false
    },
    form: {
      show: true
    },
    detail: {
      show: false
    },
    table: {
      show: false
    }
  },
  {
    field: 'dept_id',
    width: '110px',
    label: t('formZD.department'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await departmentSelect({})
        let list: any = []

        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        AddressList.value = list
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      api: async () => {
        const res: any = await departmentSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    }
  },

  {
    field: 'workplace',
    width: '100px',
    label: t('formZD.workLocation'),
    search: {
      show: true
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'job',
    width: '110px',
    label: t('personnelManagementemp.post'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'mobile',
    width: '120px',
    label: t('descriptionsDemo.phone'),
    search: {
      show: false
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },

  {
    field: 'phone',
    width: '120px',
    label: t('personnelManagementemp.workPhone'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'code',
    width: '90px',
    label: t('formZD.departmentCode'),
    search: {
      show: false
    },
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'entrytime',
    width: '120px',
    label: t('staff.entryTime'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'officialtime',
    width: '120px',
    label: t('personnelManagementemp.probationTime'),
    search: {
      show: false
    },
    form: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    detail: {
      show: true
    }
  },
  {
    field: 'leavetime',
    width: '120px',
    label: t('personnelManagementemp.leavetime'),
    form: {
      show: true
    },
    detail: {
      show: false
    }
  },
  {
    field: 'social_security_time',
    width: '180px',
    label: t('personnelManagementemp.paymentTimeOfSocialSecurity'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },

  {
    field: 'age',
    width: '80px',
    label: t('personnelManagementemp.cage'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'age',
    width: '80px',
    label: t('personnelManagementemp.mounthage'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'birth',
    width: '120px',
    label: t('personnelManagementemp.dataOfBirth'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'cardno',
    width: '180px',
    label: t('personnelManagementemp.idNo'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'gender',
    width: '80px',
    label: t('personnelManagementemp.gender'),
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true,
        options: sex
      }
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        filterable: true,
        options: sex
      }
    },
    detail: {
      show: true
    }
  },
  {
    field: 'social_security',
    width: '90px',
    label: t('personnelManagementemp.whetherToPaySocialSecurity'),
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true,
        options: [
          { label: '未缴纳', value: '0' },
          { label: '已缴纳', value: '1' },
          { label: '无', value: '2' }
        ]
      }
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        filterable: true,
        options: [
          { label: '未缴纳', value: '0' },
          { label: '已缴纳', value: '1' },
          { label: '无', value: '2' }
        ]
      }
    },
    detail: {
      show: true
    }
  },
  {
    field: 'insuredtime',
    width: '180px',
    label: t('personnelManagementemp.insurancePeriod'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'insurancePeriod',
    width: '80px',
    label: t('personnelManagementemp.age'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'census',
    width: '150px',
    label: t('personnelManagementemp.registeredResidence'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'census_type',
    width: '100px',
    label: t('personnelManagementemp.natureOfRegisteredResidence'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'address',
    width: '180px',
    label: t('personnelManagementemp.firstResidenceAddress'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'politics',
    width: '80px',
    label: t('personnelManagementemp.politicalOutlook'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'marital',
    width: '80px',
    label: t('personnelManagementemp.maritalStatus'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },

  {
    field: 'bear',
    width: '80px',
    label: t('personnelManagementemp.fertilityStatus'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'education',
    width: '80px',
    label: t('personnelManagementemp.educationing'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'schooltag',
    width: '120px',
    label: t('personnelManagementemp.education'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'major',
    width: '100px',
    label: t('personnelManagementemp.majorStudied'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'pactstart',
    width: '150px',
    label: t('personnelManagementemp.contractStartTime'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'pactend',
    width: '150px',
    label: t('personnelManagementemp.contractDeadline'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'exigency',
    width: '80px',
    label: t('personnelManagementemp.emergencyContact'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'exigency_mobile',
    width: '150px',
    label: t('personnelManagementemp.emergencyContactPhone'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'bank',
    width: '120px',
    label: t('personnelManagementemp.bank'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'bankno',
    width: '180px',
    label: t('personnelManagementemp.bankAccout'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'remark',
    width: '80px',
    label: t('personnelManagementemp.notes'),
    form: {
      show: true
    },
    detail: {
      show: true
    }
  },
  {
    field: 'email',
    width: '100px',
    label: t('descriptionsDemo.email'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'createtime',
    width: '120px',
    label: t('personnelManagementemp.createtime'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'updatetime',
    width: '120px',
    label: t('personnelManagementemp.updatetime'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },

  {
    field: 'deletetime',
    width: '120px',
    label: t('personnelManagementemp.deletetime'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const AddAction = (rlues) => {
  if (checkRlues(rlues)) push('/personnelManagement/staffAdd')
}

const delLoading = ref(false)

const delData = async (row: TableData | null, multiple: boolean, rlus: string) => {
  if (!checkRlues(rlus)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = (row: TableData, type: string, rlus: string) => {
  if (!checkRlues(rlus)) return false
  switch (type) {
    case 'Edit':
      {
        push(`/personnelManagement/staff${type}?id=${row.id}`)
      }
      break
    default:
      break
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      const res = await empEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
const selSshebao = (id) => {
  if (id) {
    let list = [
      { label: '未缴纳', value: '0' },
      { label: '已缴纳', value: '1' },
      { label: '无', value: '2' }
    ]
    let data: any = list.find((item: any) => {
      return String(item.value) == id
    })
    return data.label
  } else {
    return ''
  }
}
const selAddress = (id) => {
  if (id) {
    let list = AddressList.value
    let data: any = list.find((item: any) => {
      return item.value == id
    })
    return data && data.label
  } else {
    return ''
  }
}
const selSex = (id) => {
  if (id) {
    let list = [
      { label: '男', value: '0' },
      { label: '女', value: '1' }
    ]
    let data: any = list.find((item: any) => {
      return String(item.value) == id
    })
    return data.label
  } else {
    return ''
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction('16-1')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #dept_id="{ row }"> {{ selAddress(row.dept_id) }} </template>
      <template #gender="{ row }"> {{ selSex(row.gender) }} </template>
      <template #social_security="{ row }"> {{ selSshebao(row.social_security) }} </template>
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'Edit', '16-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row, false, '16-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>
</template>
